package com.mxin.network.factory

import androidx.lifecycle.LiveData
import com.mxin.network.IBaseResponse
import retrofit2.CallAdapter
import retrofit2.Response
import retrofit2.Retrofit
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

/**
 *  Created by ：2020/7/29
 *  author : Administrator
 *
 */
class LiveDataCallAdapterFactory(private val logicListener:LiveDataCallAdapterLogicListener<Any>): CallAdapter.Factory() {
    override fun get(
        returnType: Type,
        annotations: Array<Annotation>,
        retrofit: Retrofit
    ): CallAdapter<*, *>? {
        val responseType:Type
        if(getRawType(returnType) != LiveData::class.java){
            return null
        }
        //获取第一个泛型类型
        val observableType = getParameterUpperBound(0, returnType as ParameterizedType)
        val rawType  = getRawType(observableType)
        responseType = if(rawType == Response::class.java){
            if(observableType !is ParameterizedType){
                throw IllegalStateException("Response must be parameterized")
            }
            getParameterUpperBound(0, observableType)
        }else{
            observableType
        }
        return LiveDataCallAdapter<Any>(responseType, logicListener)
    }
}